package com.kiell.cubemall.product.controller;

import com.kiell.cubemall.common.utils.PageUtils;
import com.kiell.cubemall.common.utils.R;
import com.kiell.cubemall.product.entity.BrandEntity;
import com.kiell.cubemall.product.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


/**
 * 品牌表
 *
 * @author kiell
 * @email sunlightcs@gmail.com
 * @date 2022-01-12 16:44:46
 */
@RestController
@RequestMapping("product/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = brandService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id){
		BrandEntity brand = brandService.getById(id);

        return R.ok().put("brand", brand);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@Valid @RequestBody BrandEntity brand,BindingResult result){
        if (result.hasErrors()){
            Map<String,String> map = new HashMap<>();
            //1.获取校验错误结果
            result.getFieldErrors().forEach(fieldError -> {
                //获取每个错误的属性名字
                String field = fieldError.getField();
                //获取每个错误提示信息
                String defaultMessage = fieldError.getDefaultMessage();
                map.put(field,defaultMessage);
            });
            return R.error(400,"提交信息不合法").put("data",map);
        }else{
		    brandService.save(brand);
        }

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody BrandEntity brand){
		brandService.updateById(brand);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids){
		brandService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
